#include "memwindow.h"
#include "ui_memwindow.h"
#include "adminwindow.h"
#include <QFile>
#include <QMessageBox>

MemWindow::MemWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MemWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("成员管理");
}

MemWindow::~MemWindow()
{
    delete ui;
}

void MemWindow::on_returnButton_clicked()
{
    AdminWindow* aw = new AdminWindow;
    this->close();
    aw->show();
}

void MemWindow::on_okButton_clicked()
{
    //1.如果文件不存在，则创建文件并将数据写入的文件中
    QFile file("./user.txt");

    if(file.open(QIODevice::WriteOnly | QIODevice::Append))
    {

        //2.获取用户输入的名字和密码
         QString name = ui->namelineEdit->text();
         QString password = ui->passwordlineEdit->text();

         if(ui->namelineEdit->text() == "" || ui->passwordlineEdit->text() == "")
         {
             QMessageBox::information(this,"提示","请规范输入信息");
             return;
         }

         //3.将数据打包
         name = name.append("\r\n");
         password = password.append("\r\n");

         name = name + password; // "用户名\r\n密码\r\n"
         //4.将数据写入到文件
         file.write(name.toUtf8());

         QMessageBox::information(this,"注册提示","注册成功");
    }

    //关闭文件
    file.close();

}


void MemWindow::on_flashButton_clicked()
{

    QFile file1("./user.txt");
    if(file1.open(QIODevice::ReadOnly))
    {


        while (!file1.atEnd())
        {

            QString name =  file1.readLine(); //用户名\r\n
            name = name.remove("\r\n"); //用户名
            QListWidgetItem *item = new QListWidgetItem(name);
            ui->detaillistWidget->addItem(item);
        }
    }
}

void MemWindow::on_delButton_clicked()
{
    QFile file("./user.txt");

    if(file.open(QIODevice::WriteOnly))
    {
        if(QMessageBox::Yes == QMessageBox::question(this,"Warning","是否删除目标信息"))
        {
            QListWidgetItem* item = ui->detaillistWidget->currentItem();
            ui->detaillistWidget->removeItemWidget(item);
            delete item;
        }

     QString name = ui->namelineEdit->text();
     QString password = ui->passwordlineEdit->text();


     name = name.append("\r\n");
     password = password.append("\r\n");

     name = name + password;
     file.write(name.toUtf8());


    }

    //关闭文件
    file.close();

}
